package cn.ac.iscas.baseline;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashSet;

public class Forward {
	static HashSet<String> dict = new HashSet<String>();
	public static void main(String[] args) throws IOException{
		Train("data/pku_training.utf8");
		PrintStream ps = new PrintStream(
	            new BufferedOutputStream(new FileOutputStream(
	            new File("data/result_forward.txt"))), true);
		System.setOut(ps); 
		Test("data/pku_test.utf8");
	}
	
	static void Train(String path) throws IOException{
		FileReader reader = new FileReader(
		path);
		BufferedReader br = new BufferedReader(reader);
		String line = null;
	
		while ((line = br.readLine()) != null) {
			trainLine(line);
		}
		br.close();
		reader.close();        
	}
	
	static void trainLine(String line){
		String[] tmp = line.split(" ");
		for (int i = 0; i < tmp.length; i++){
			if (!dict.contains(tmp[i])){
				dict.add(tmp[i]);
			}
		}
	}
	
	static void Test(String path) throws IOException{
		FileReader reader = new FileReader(
		path);
		BufferedReader br = new BufferedReader(reader);
		String line = null;
	
		while ((line = br.readLine()) != null) {
			testLine(line);
		}
		br.close();
		reader.close();  		
	}
	
	static void testLine(String line){
		while (line.length() > 0){
			String substr = "";
			for (int i = line.length(); i > 0; i--){
				substr = line.substring(0, i);
				if (dict.contains(substr) || substr.length() == 1){
					System.out.print(convertStr(substr) + "| ");
					break;
				}
			}
			line = line.substring(substr.length(), line.length());
		}
		System.out.println();
	}
	
	static String convertStr(String input){
		String output = "";
		for (int i = 0; i < input.length(); i++){
			output += input.charAt(i) + " ";
		}
		return output;
	}
}
